<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="模板类型" prop="templateType">
        <el-select v-model="queryParams.templateType" placeholder="请选择模板类型" clearable>
          <el-option
            v-for="dict in dict.type.template_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="模板文件路径" prop="filePath">
        <el-input
          v-model="queryParams.filePath"
          placeholder="请输入模板文件路径"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模板文件类型" prop="fileType">
        <el-select v-model="queryParams.fileType" placeholder="请选择模板文件类型" clearable>
          <el-option
            v-for="dict in dict.type.template_file_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="数据源id" prop="jdbcConfigId">
        <el-input
          v-model="queryParams.jdbcConfigId"
          placeholder="数据源id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="表名" prop="tableName">
        <el-input
          v-model="queryParams.tableName"
          placeholder="请输入表名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['importExport:template:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['importExport:template:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['importExport:template:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['importExport:template:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="templateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="模板类型" align="center" prop="templateType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.template_type" :value="scope.row.templateType"/>
        </template>
      </el-table-column>
      <el-table-column label="模板文件路径" align="center" prop="filePath" />
      <el-table-column label="模板文件类型" align="center" prop="fileType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.template_file_type" :value="scope.row.fileType"/>
        </template>
      </el-table-column>
      <el-table-column label="字典映射" show-overflow-tooltip align="center" prop="dict" />
      <el-table-column label="样式" show-overflow-tooltip align="center" prop="style" />
      <el-table-column label="备注" show-overflow-tooltip align="center" prop="remark" />
      <el-table-column label="数据源id" align="center" prop="jdbcConfigId" />
      <el-table-column label="导入的表名" align="center" prop="tableName" />
      <el-table-column label="创建时间" show-overflow-tooltip align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="small" v-if="scope.row.templateType == '2' && scope.row.fileType == '2'" type="primary"
            @click="handleUploadExcelTemplate(scope.row)"">上传模板</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['importExport:template:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['importExport:template:remove']"
          >删除</el-button>
          <el-button size="small" v-if="scope.row.templateType == '2' && scope.row.fileType == '2' && scope.row.filePath != undefinde && scope.row.filePath != ''" type="info"
            @click="handleDownlodaFileById(scope.row)"">下载模板</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 上传模板对话框 -->
    <el-dialog :title="title" :visible.sync="templateUpload" width="400px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-upload
          ref="upload"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?id=' + form.id"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip text-center" slot="tip">
            <span>仅允许导入xls、xlsx格式文件。</span>
          </div>
        </el-upload>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitTemplateForm">确 定</el-button>
        <el-button @click="handleCanle">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改导入导出模板对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="模板类型" prop="templateType">
          <el-select v-model="form.templateType" placeholder="请选择模板类型">
            <el-option
              v-for="dict in dict.type.template_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
       <el-form-item v-if="form.templateType == 2" label="模板文件类型" prop="fileType">
          <el-select v-model="form.fileType" placeholder="请选择模板文件类型">
            <el-option
              v-for="dict in dict.type.template_file_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="字典映射" prop="dict">
          <el-input v-model="form.dict" type="textarea" placeholder="请输入内容(json或yaml格式)" />
        </el-form-item>
        <el-form-item label="样式" prop="style">
          <el-input v-model="form.style" type="textarea" placeholder="请输入内容(json或yaml格式)" />
        </el-form-item>
        <el-form-item label="数据源" prop="jdbcConfigId">
          <el-select v-model="form.jdbcConfigId" filterable @change="selectTable(form.jdbcConfigId)" placeholder="请选择数据源">
            <el-option
              v-for="item in datasources"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="表名" prop="tableName">
          <el-select v-model="form.tableName" filterable placeholder="请选择导入的表名">
            <el-option
              v-for="item in tables"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTemplate, getTemplate, delTemplate, addTemplate, updateTemplate, uploadExcelTemplate } from "@/api/importExport/template";
import { getToken } from "@/utils/auth";
import { listDatasource, listTables } from "@/api/importExport/task";
export default {
  name: "Template",
  dicts: ['template_type', 'template_file_type'],
  data() {
    return {
      //控制上传按钮
      uploadDisabled: false,
      templateUpload: false,
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/importExport/template/uploadExcelTemplate"
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 导入导出模板表格数据
      templateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        templateType: null,
        filePath: null,
        fileType: null,
        dict: null,
        style: null,
        isdelete: null,
        jdbcConfigId: null,
        tableName: null
      },
      // 表单参数
      form: {

      },
      // 数据源列表
      datasources: [],
      // 表
      tables: [],          
      // 表单校验
      rules: {
        templateType: [
          { required: true, message: "模板类型不能为空", trigger: "blur" }
        ],
        jdbcConfig: [
          { required: true, message: "数据源不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.listDatasource();
  },
  methods: {
    //根据数据源获取该库的所有表
    selectTable(id){
      listTables(id).then(response => {
        this.tables = response.data;
      });
    },
    /** 查询导入导出任务列表 */
    listDatasource() {
      listDatasource().then(response => {
        this.datasources = response.data;
      });
    },
    submitTemplateForm(){
      var fileList = this.$refs.upload.uploadFiles
      if(fileList.length <= 0){
        this.$modal.msgError("请先上传导入文件");
        return;
      }
      this.$refs.upload.submit().then()
    },
    //取消导入
    handleCanle(){
      this.templateUpload = false;
      this.form.id = null;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
    },
    /** 模板id 上传oss模板文件 */
    handleUploadExcelTemplate(row){
      this.form.id = row.id;
      this.templateUpload = true;
      this.title = "id【"+this.form.id+"】上传excel模板文件";
    },
    /** 模板id 下载oss模板文件 */
    handleDownlodaFileById(row){
      var filePath = row.filePath
      var fileName = filePath.substring(filePath.lastIndexOf('/') + 1)
      this.download('importExport/template/downlodaTemplateOssFileById?id='+row.id+'&fileName=' + fileName,{},fileName)
    },
    /** 查询导入导出模板列表 */
    getList() {
      this.loading = true;
      listTemplate(this.queryParams).then(response => {
        this.templateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.upload.open = false;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        templateType: null,
        filePath: null,
        fileType: null,
        dict: null,
        style: null,
        remark: null,
        isdelete: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        jdbcConfigId: null,
        tableName: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加导入导出模板";
      this.upload.open = true;
      this.listDatasource();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.listDatasource();
      this.reset();
      const id = row.id || this.ids
      getTemplate(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改导入导出模板";
      });
    },
    // 文件上传成功处理
    handleFileSuccess(response) {
      if(response.code == 200){
        this.templateUpload = false;
        this.form.id = null;
        this.getList();
        this.$modal.msgSuccess("上传成功");
        this.$refs.upload.clearFiles();
      }else{
        this.$modal.msgError(response.msg);
      }
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTemplate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTemplate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除导入导出模板编号为"' + ids + '"的数据项？').then(function() {
        return delTemplate(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('importExport/template/export', {
        ...this.queryParams
      }, `template_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
